/*
 * Copyright 2007 National Bioinformatics Network
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package dgbgui.modeldocument.uimodels;

import javax.swing.DefaultComboBoxModel;

import dgbgui.modeldocument.ModelDocument;
import dgbgui.modeldocument.Query;

/**
 * @author bjnortier
 * Combo model for selecting queries
 */
@SuppressWarnings("serial")
public class QueryComboModel extends DefaultComboBoxModel {
    
    
    /**
     * Default constructor. Add all the current queries
     */
    public QueryComboModel() {
        addAllQueries(this);
    }
    
    /**
     * Construct the model with a query. If it is not in the
     * model, it will be added. The query is set as the current one
     * @param query The current query
     */
    public QueryComboModel(Query query) {
        this();

        boolean found = false;
        for ( int k = 0; k < getSize(); ++k ) {
            if ( ((QueryComboItem)getElementAt(k)).getQuery() ==  query ) {
                setSelectedItem(getElementAt(k));
                found = true;
                break;
            }
        }
        
        // If the query was not found, add it to the model
        // and set it as selected
        if ( !found ) {
            QueryComboItem newItem = new QueryComboItem(query);
            addElement(newItem);
            setSelectedItem(newItem);
        }
    }



    /**
     * Remove a query from the model
     * @param query
     */
    public void removeQuery(Query query) {
        for ( int k = 0; k < getSize(); ++k ) {
            if ( ((QueryComboItem)getElementAt(k)).getQuery() ==  query ) {
                removeElementAt(k);
                break;
            }
        }
    }
    
    /**
     * @return The selected query
     */
    public Query getSelected() {
        return ((QueryComboItem)getSelectedItem()).getQuery();
    }
    
    /**
     * 
     */
    public static void addAllQueries(DefaultComboBoxModel  model) {
        for ( Query q : ModelDocument.getInstance().getAllQueries() ) {
            model.addElement(new QueryComboItem(q));
        }
        
    }

}
